<template>
  <div class="chat-window">
    <!-- 聊天窗口头部 -->
    <div class="chat-header">
      <div class="chat-title" v-if="currentContact">
        {{ currentContact.name }}
      </div>
    </div>

    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messageContainer">
      <!-- 消息列表 -->
      <div v-for="(msg, index) in currentMessages" :key="index" class="message-item">
        <!-- 时间分割线 -->
        <div v-if="shouldShowTimeDivider(index)" class="time-divider">
          {{ formatTimeDivider(msg.time) }}
        </div>

        <!-- 消息气泡 -->
        <div :class="['message-wrapper', msg.isSelf ? 'self-message' : 'other-message']">
          <div class="message-avatar">
            <!-- 核心：仅使用消息中的avatarUrl，添加默认头像兜底 -->
            <img :src="msg.avatarUrl || defaultAvatar" alt="用户头像" @error="handleAvatarError(msg)" />
          </div>

          <div class="message-content-container">
            <div class="message-content-wrapper">
              <div class="message-bubble" :style="{ 'background-color': msg.isSelf ? '#95ec69' : '#ffffff' }">
                <div class="message-text">
                  {{ msg.content }}
                </div>
              </div>
            </div>
            <div class="message-sender" v-if="!msg.isSelf">
              {{ msg.sender }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input-area" v-if="currentContact">
      <input v-model="inputValue" type="text" placeholder="输入消息..." class="chat-input" @keyup.enter="sendMessage" />
      <button class="send-btn" @click="sendMessage">发送</button>
    </div>
    <!-- 弹窗区域 -->
    <transition-group name="message-popup" class="message-popup-container" tag="div">
      <div v-for="(popupMsg, index) in visiblePopupMessages" :key="popupMsg.id" class="message-popup">
        <div class="popup-content">
          <div class="popup-sender">{{ popupMsg.sender }}：</div>
          <div class="popup-text">{{ popupMsg.content }}</div>
        </div>
      </div>
    </transition-group>
  </div>
</template>

<script setup>
import { ref, watch, onUnmounted, onMounted, defineProps, defineEmits, nextTick } from 'vue';
import request from '../utils/request';

// 定义默认头像（当消息中无avatarUrl时使用）
const defaultAvatar = '/images/avatar-default.png';

// 定义 props 和 emits
const props = defineProps({
  contact: {
    type: Object,
    default: () => ({})
  }
});
const emit = defineEmits(['message-sent']);

// 状态管理
const currentMessages = ref([]);   // 聊天消息列表
const currentContact = ref(null); // 当前聊天对象
const inputValue = ref('');       // 输入框内容
const messageContainer = ref(null); // 消息容器 DOM
const popupMessages = ref([]); // 存储需要弹窗的消息
const visiblePopupMessages = ref([]); // 控制正在显示的弹窗
let popupTimer = null; // 定时器标识
const mountTime = ref(null); // 组件挂载时间

onMounted(() => {
  mountTime.value = new Date();
  // 初始化时强制触发一次滚动（处理容器高度问题）
  nextTick(() => {
    scrollToBottom();
  });
});

/**
 * 加载历史消息（仅使用消息中的avatarUrl）
 */
const loadMessages = async (dialogueId) => {
  try {
    const response = await request.get('/user/getmessage', { params: { dialogueId } });
    if (response.data.code === 'SUCCESS') {
      currentMessages.value = response.data.data.map(msg => {
        const msgTime = new Date(msg.sendTime);
        return {
          content: msg.content,
          time: msg.sendTime,
          sender: msg.userName,
          // 仅使用消息中的avatarUrl，不依赖本地存储
          avatarUrl: msg.avatarUrl,
          isSelf: msg.id === parseInt(localStorage.getItem('userId')),
          isRead: true,
          isAfterMount: msgTime >= mountTime.value
        };
      });
      nextTick(() => scrollToBottom());
    }
  } catch (error) {
    console.error('获取消息失败:', error);
  }
};

//defineExpose({ loadMessages });
const addMessage = (newMessage) => {
  currentMessages.value = [...currentMessages.value, newMessage];
  nextTick(scrollToBottom);
};

// 暴露给父组件
defineExpose({ loadMessages, addMessage });
// 监听contact变化，加载对应消息
watch(() => props.contact, (newContact) => {
  if (newContact && newContact.dialogueId) {
    currentContact.value = newContact;
    loadMessages(newContact.dialogueId);
  }
}, { immediate: true });

/**
 * 发送消息逻辑（确保本人发送的消息使用本人头像）
 */
const sendMessage = async () => {

  const content = inputValue.value.trim();
  if (!content || !currentContact.value) return;

  try {
    console.log('[sendMessage] 当前会话信息:', {
      id: currentContact.value.id,
      name: currentContact.value.name,
      avatar: currentContact.value.avatar,
      userId: currentContact.value.userId
    });

    // 总是使用本人的头像（无论当前联系人是谁）
    const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
    const avatarUrl = userInfo.avatarUrl || '/images/avatar-self.png';

    // 构建新消息
    const newMessage = {
      content: content,
      time: new Date().toISOString(),
      isSelf: true, // 这是本人发送的消息
      avatarUrl: avatarUrl, // 使用本人头像
      sender: localStorage.getItem('userName') || '我',
      isRead: true,
      isAfterMount: true
    };

    console.log('[sendMessage] 构造的新消息:', newMessage);

    // 添加新消息
    currentMessages.value = [...currentMessages.value, newMessage];
    inputValue.value = '';

    // 等待DOM更新后再滚动（只需要一次nextTick）
    await nextTick();
    scrollToBottom();
    console.log('[sendMessage] 已滚动到底部');

    // 触发父组件事件
    emit('message-sent', {
      contactId: currentContact.value.id,
      message: newMessage
    });
  } catch (error) {
    console.error('发送消息失败:', error);
  }
};

/**
 * 头像加载错误处理（兼容base64和URL失败的情况）
 */
const handleAvatarError = (msg) => {
  console.error(`头像加载失败（${msg.avatarUrl || '无URL'}），已替换为默认头像`);
  // 强制使用默认头像
  msg.avatarUrl = defaultAvatar;
};

/**
 * 滚动到消息底部
 */
const scrollToBottom = () => {
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
  }
};

/**
 * 格式化消息时间（时:分）
 */
const formatTime = (timeStr) => {
  const date = new Date(timeStr);
  if (isNaN(date.getTime())) return timeStr;
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

/**
 * 判断是否显示时间分割线（间隔>5分钟）
 */
const shouldShowTimeDivider = (index) => {
  if (index === 0) return true;
  const currentTime = new Date(currentMessages.value[index].time);
  const prevTime = new Date(currentMessages.value[index - 1].time);
  return (currentTime - prevTime) / (1000 * 60) > 5;
};

/**
 * 格式化时间分割线（月 / 日 时:分）
 */
const formatTimeDivider = (time) => {
  const date = new Date(time);
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${month}/${day} ${hours}:${minutes}`;
};

// 监听新消息，处理弹窗
watch(currentMessages, (newMessages) => {
  const unreadNewMessages = newMessages.filter(
    msg => !msg.isSelf && !msg.isRead && msg.isAfterMount
  );
  if (unreadNewMessages.length > 0) {
    unreadNewMessages.forEach(msg => {
      const msgId = Date.now() + Math.random();
      popupMessages.value.push({ ...msg, id: msgId });
    });
    showPopupMessages();
  }
}, { deep: true });

/**
 * 显示弹窗消息
 */
const showPopupMessages = () => {
  if (popupMessages.value.length > 0) {
    const msg = popupMessages.value.shift();
    visiblePopupMessages.value.push(msg);
    popupTimer = setTimeout(() => {
      const index = visiblePopupMessages.value.findIndex(item => item.id === msg.id);
      if (index !== -1) visiblePopupMessages.value.splice(index, 1);
      showPopupMessages();
    }, 3000);
  }
};

</script>

<style scoped>
/* 聊天窗口基础样式 */
.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.6);
}

/* 头部样式 */
.chat-header {
  padding: 15px;
  border-bottom: 1px solid #ffffff;
  font-weight: bold;
  font-size: 16px;
}

/* 消息区域 */
.chat-messages {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

/* 时间分割线 */
.time-divider {
  text-align: center;
  margin: 16px 0;
}

.time-divider span {
  display: inline-block;
  padding: 4px 12px;
  background: linear-gradient(to bottom, #f5f5f5, #e8e8e8);
  color: #666;
  font-size: 12px;
  border-radius: 16px;
  line-height: 1;
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05),
    inset 0 1px 1px rgba(255, 255, 255, 0.8);
  border: 1px solid #ddd;
  transition: all 0.2s ease;
}

.time-divider span:hover {
  transform: translateY(-1px);
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.08),
    inset 0 1px 2px rgba(255, 255, 255, 0.9);
}

/* 气泡 */
.message-bubble {
  position: relative;
  padding: 8px 12px;
  border-radius: 10px;
  font-size: 14px;
  line-height: 1.6;
  word-wrap: break-word;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  min-width: 30px;
  /* 最小宽度，避免过窄 */
  display: inline-block;
  /* 根据内容宽度自适应 */
}

/* 气泡箭头：使用 transform 确保垂直居中 */
.message-bubble::before {
  content: '';
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 0;
  height: 0;
  border-style: solid;
}

/* 自己的消息：右对齐 */
.self-message {
  flex-direction: row-reverse;
  /* 反转顺序，头像在右 */
  justify-content: flex-start;
  /* 内容靠左（因为反转后实际是靠右） */
  align-self: flex-end;
  /* 整体靠右对齐 */
}

/* 自己消息的箭头 */
.self-message .message-bubble::before {
  right: -8px;
  border-width: 6px 0 6px 8px;
  border-color: transparent transparent transparent #95ec69;
}

/* 对方的消息：左对齐 */
.other-message {
  flex-direction: row;
  justify-content: flex-start;
  align-self: flex-start;
}

/* 对方消息的箭头 */
.other-message .message-bubble::before {
  left: -8px;
  border-width: 6px 8px 6px 0;
  border-color: transparent #ffffff transparent transparent;
}

/* 头像样式 */
.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin: 0 10px;
  /* 统一头像与气泡的间距 */
  flex-shrink: 0;
  /* 防止头像被压缩 */
}

.message-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 消息内容容器 */
.message-content-container {
  display: flex;
  flex-direction: column;
  max-width: calc(100% - 56px);
  /* 为头像预留空间 */
}

/* 气泡包装器：控制气泡与头像的间距 */
.message-content-wrapper {
  position: relative;
}

/* 发送者名称 */
.message-sender {
  font-size: 12px;
  color: #434242;
  margin-bottom: 2px;
  padding-left: 4px;
}

/* 消息文本 */
.message-text {
  padding: 8px 12px;
  border-radius: 10px;
  font-size: 14px;
  line-height: 1.6;
  word-wrap: break-word;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

/* 输入区域 */
.chat-input-area {
  display: flex;
  padding: 10px;
  border-top: 1px solid #e5e5e5;
}

.chat-input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
}

.send-btn {
  padding: 8px 16px;
  background-color: #07c160;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.send-btn:hover {
  background-color: #05a650;
}

/* 消息包装器：控制整体方向 */
.message-wrapper {
  display: flex;
  align-items: flex-start;
  max-width: 100%;
}

/* 新增：确保消息项垂直排列，避免挤压 */
.message-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
}

/*弹窗*/
.message-popup-container {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 280px;
  pointer-events: none;
  /* 避免遮挡下方操作 */
}

.message-popup {
  background-color: rgba(255, 255, 255, 0.7);
  color: #333;
  padding: 12px 16px;
  margin-bottom: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  pointer-events: auto;
  /* 恢复鼠标事件 */
  animation: slideIn 0.3s ease-in-out;
}

.message-popup .popup-content {
  display: flex;
  flex-direction: column;
}

.message-popup .popup-sender {
  font-weight: bold;
  margin-bottom: 4px;
  color: #07c160;
}

.message-popup .popup-text {
  font-size: 14px;
  line-height: 1.4;
}

/* 弹窗进入动画 */
@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }

  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 过渡动画（配合 transition-group） */
.message-popup-enter-active,
.message-popup-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.message-popup-enter-from,
.message-popup-leave-to {
  opacity: 0;
  transform: translateX(100%);
}

.message-popup-enter-to,
.message-popup-leave-from {
  opacity: 1;
  transform: translateX(0);
}
</style>